<template>
  <div class="app-container">
    <el-dialog
      :title="'设置图片热区'"
      top="20"
      :visible.sync="dialog"
      :close-on-click-modal="false"
      :before-close="cancel"
      append-to-body
      width="70%"
    >
      <div class="hotzone" style="display: flex">
        <hotzone
          ref="hotzone"
          style="width: 30vw"
          :image="image"
          :zonesInit="rowInfo.hotZone"
          @add="handleAdd"
          @remove="handleRemove"
          @change="handleChange"
        ></hotzone>

        <el-form :model="rowInfo" label-width="100px" style="flex: 1">
          <el-form-item
            v-for="(item, index) in rowInfo.hotZone"
            :prop="'hotZone[' +index+ '].url'"
            :label="`链接${index + 1}`"
            :key="index"
            :rules="{ type: 'url', message: '请输入正确的地址', trigger: 'blur' }"
          >
            <el-input v-model="item.url"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import hotzone from '@/components/HotZone'
import { update } from '@/api/business/mediaApi'

export default {
  components: {
    hotzone
  },
  data: function() {
    return {
      loading: false,
      dialog: false,
      image: '',
      rowInfo: {}
    }
  },
  methods: {
    cancel() {
      this.dialog = false
      this.$refs.hotzone.zones = []
      this.rowInfo = {}
      this.image = ''
    },
    setup(row) {
      this.dialog = true
      this.image = row.url[0].url
      this.rowInfo = JSON.parse(JSON.stringify(row))
      this.rowInfo.hotZone = this.rowInfo.hotZone ? this.rowInfo.hotZone : []

      this.$nextTick(() => {
        this.$refs.hotzone.zones = JSON.parse(JSON.stringify(this.rowInfo.hotZone))
      })
    },
    handleAdd(zone) {
      const last = this.rowInfo.hotZone[this.rowInfo.hotZone.length - 1]
      if (JSON.stringify(last) !== JSON.stringify(zone)) {
        this.rowInfo.hotZone.push(zone)
      }
    },
    handleRemove(index) {
      this.rowInfo.hotZone.splice(index, 1)
    },
    handleChange(zone) {
      // eslint-disable-next-line
      // console.log('Zones data updated')
      this.rowInfo.hotZone = zone
    },
    getZoneStyle(val) {
      return `${(val || 0) * 100}%`
    },
    doSubmit() {
      console.log(this.rowInfo)
      this.loading = true
      update(this.rowInfo)
        .then(res => {
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.$parent.init()
          this.cancel()
        })
        .catch(err => {
          this.loading = false
        })
    }
  }
}
</script>

<style>
</style>
